package com.thirtydays.frame.ui.recycle

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_MOVE
import android.view.MotionEvent.ACTION_UP
import android.view.ViewParent
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import kotlin.math.abs

/**
 * @author 小垚
 * @创建时间： 2021/4/14
 * @描述：viewpage2嵌套横向的RecyclerView
 **/
class HorizontalRecyclerView : RecyclerView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private var x1 = 0f
    private var y1 = 0f
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        //解决recyclerView和viewPager的滑动影响
        //当滑动recyclerView时，告知父控件不要拦截事件，交给子view处理
        get(false);
        when (ev!!.action) {
            MotionEvent.ACTION_DOWN -> {
                x1 = ev.x;
                y1 = ev.y;
            }
            ACTION_MOVE -> {
                var x2 = ev.x;
                var y2 = ev.y;
                var offsetX = abs(x2 - x1)
                var offsetY = abs(y2 - y1)
                get(offsetX < offsetY)
            }
            ACTION_UP -> {
                x1 = y1 - 0
                get(true)
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private var mViewParent: ViewParent? = null

    //使用迭代 直至找到parent是NoScrollViewPager为止
    //效率有些低 偏low 莫见怪
    private fun get(isEnable: Boolean) {
        mViewParent = if (mViewParent == null)
            parent;
        else
            mViewParent!!.parent;


        if (mViewParent is ViewPager2) {
            //true 禁止ViewPager滑动，自动交给recyclerview去滑动
            //false 交给ViewPager滑动
            (mViewParent as ViewPager2).isUserInputEnabled = isEnable

        } else {
            get(isEnable);
        }
    }
}